package com.yunhe.authority.service.base.impl;

import com.yunhe.authority.domain.base.Feedback;
import com.yunhe.authority.repository.base.FeedbackRepository;
import com.yunhe.authority.service.base.FeedbackService;
import com.yunhe.authority.util.SendHttps;
import com.yunhe.common.util.DateTimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhengbo
 * @date 2021/5/20 16:05
 */
@Service
@Slf4j
public class FeedbackServiceImpl implements FeedbackService {

    @Autowired
    private FeedbackRepository feedbackRepository;

    //正式环境
    private  static String dingDingToken="https://oapi.dingtalk.com/robot/send?access_token=8f5d1aedf58f30fc9527da8c86f76f03df8831dafe9ed0b3f1c4628204c050c2";
    private static String secret = "SECdcad8c571fd16abe42e1d80f7665eb01813c9bf28843ba2cd412bd4eec27d5be";

    //测试环境
    //private  static String dingDingToken="https://oapi.dingtalk.com/robot/send?access_token=3b6c1461599702030d6828ece05e28e0416e40a7b6e5dc259535d48fc5b9c363";
    //private static String secret = "SEC958172830a5213d66bad51458c6e247eb932f82d4dae21c6feaea3117458c73e";

    @Override
    public Feedback creatFeedback(Feedback feedback) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        Long timestamp = System.currentTimeMillis();
        dingDingToken +="&timestamp="+timestamp;
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)),"UTF-8");
        dingDingToken +="&sign="+sign;
        // 请求的JSON数据，这里我用map在工具类里转成json格式
        Map<String,Object> json=new HashMap();
        Map<String,Object> text=new HashMap();
        json.put("msgtype","text");
        text.put("content",feedback.getUsername()+"在"+feedback.getCreateTime()+
                "反馈了<"+feedback.getContent()+">,如有对反馈内容存疑，请联系反馈人，反馈人的手机号为："
                +feedback.getUserPhone());
        json.put("text",text);
        // 发送post请求
        String response = SendHttps.sendPostByMap(dingDingToken, json);
        log.info("相应结果："+response);
        return feedbackRepository.save(feedback);
    }

    @Override
    public Iterable<Feedback> getList() {
        return feedbackRepository.findAll();
    }

    @Override
    public Feedback sendFeedbackForWeChat(Feedback feedback) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        Long timestamp = System.currentTimeMillis();
        feedback.setCreateTime(DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(), new Date()));
        dingDingToken +="&timestamp="+timestamp;
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)),"UTF-8");
        dingDingToken +="&sign="+sign;
        // 请求的JSON数据，这里我用map在工具类里转成json格式
        Map<String,Object> json=new HashMap();
        Map<String,Object> text=new HashMap();
        json.put("msgtype","text");
        text.put("content",feedback.getEmployeeName()+"在"+feedback.getCreateTime()+
                "反馈了<"+feedback.getContent()+">,如有对反馈内容存疑，请联系反馈人，反馈人的手机号为："
                +feedback.getUserPhone());
        json.put("text",text);
        // 发送post请求
        String response = SendHttps.sendPostByMap(dingDingToken, json);
        log.info("相应结果："+response);
        return feedbackRepository.save(feedback);
    }
}
